package edu.scau.divineplace.config.global.data.convert;

import edu.scau.divineplace.entity.enums.BaseEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.format.FormatterRegistry;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.LocalDateTime;
import java.util.HashMap;


/**
 * @Author: x1aolone
 * @Date: 2021/1/21 17:09
 * 入参为枚举类时，使用转换器将int值转换为枚举对象
 * 只能解决 URL params传参, Body传参仍然会使用默认的用下标解析, 在枚举类中使用@JsonCreator解决
 */
@Configuration
public class EnumConfig implements WebMvcConfigurer {

    @Autowired
    private EnumConverterFactory enumConverterFactory;

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory(enumConverterFactory);
    }
}

class EnumConverter<T extends BaseEnum> implements Converter<String, T> {

    private Class<T> enumType;

    public EnumConverter(Class<T> enumType) {
        this.enumType = enumType;
    }

    @Override
    public T convert(String source) {
        if (source.length() == 0) {
            return null;
        }
        return BaseEnum.typeOf(enumType, Integer.parseInt(source));
    }

}

@Component
class EnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new EnumConverter<T>(targetType);
    }

}




